<template>
	<view class="container">
		<view class="header">
			<view class="back-button" @click="goBack">
				<uni-icons type="left" size="20" color="#000"></uni-icons>
			</view>
			<view class="title">编辑资料</view>
		</view>

		<view class="avatar-container">
			<view class="img-boxs">
				<image :src="avatar" @click="handleUpImg"> </image>
				<cover-view>修改头像</cover-view>
			</view>
		</view>

		<view class="form-container">
			<view class="form-item" @click="editField('name')">
				<text class="label">姓名</text>
				<text class="value">{{ name || '请输入姓名' }}</text>
			</view>
			<view class="form-item" @click="editField('bio')">
				<text class="label">简介</text>
				<text class="value">{{ bio || '请输入简介' }}</text>
			</view>
			<view class="form-item">
				<text class="label">性别</text>
				<view class="gender-switch">
					<view class="man-icon" @click="selectGender('男')">
						<image :src="gender === '男' ? '/static/man_blue.png' : '/static/man.png'" class="man-image" />
					</view>
					<view class="woman-icon" @click="selectGender('女')">
						<image :src="gender === '女' ? '/static/woman_pink.png' : '/static/woman.png'"
							class="woman-image" />
					</view>
				</view>
			</view>
			<view class="form-item">
				<text class="label">生日</text>
				<view>
					<uni-datetime-picker type="date" v-model="birthday" :border="false" @change="onDateChange" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		editUserInfo,
		getUserInfo
	} from '@/api/user.js'; // 引入更新用户信息的接口
	export default {
		data() {
			return {
				// avatarUrl: [{
				// 	fileID: 1,
				// 	url: ''
				// }], //头像
				avatar: '',
				name: '', // 姓名
				bio: '', // 简介
				gender: '男', // 性别 (male/female)
				birthday: '',
				imageStyles: {
					width: 124,
					height: 124,
					border: {
						radius: "50%"
					}
				},
			};
		},
		onShow() {
			// 获取用户信息
			this.fetchUserInfo();
		},
		onLoad() {
			uni.$on('updateUserInfo', (updatedData) => {
				if (updatedData.name) this.name = updatedData.name;
				if (updatedData.bio) this.bio = updatedData.bio;
			});
		},
		onUnload() {
			uni.$off('updateUserInfo');
		},
		methods: {
			handleUpImg() { // 点击图片区域，选择图片并上传
				uni.chooseImage({ // 选择图片
					count: 1,
					success: (res) => { // 图片选择成功的回调（必传），会返回一个对象
						uni.uploadFile({
							url: "https://www.aaxing14.top:8101/user/file/upload", // 请求地址
							filePath: res.tempFilePaths[0], // 临时文件路径
							name: "file", // 文件对应的key值
							header: {
								'token':uni.getStorageSync('token'),
							},
							formData: { // 额外的请求数据
								'biz': 'user_avatar'
							},
							success: (res) => { // 成功后的回调
								const data = JSON.parse(res.data);
								if(data.code == 0){
									console.log("修改成功",data.data);
									this.updateUserInfo('userAvatar', data.data);
								}
							}
						})
					}
				})
			},

			async fetchUserInfo() {
				getUserInfo() // 发送获取用户信息的请求
					.then(response => {
						if (response.code == 200) {
							this.name = response.data.nickname;
							this.gender = response.data.gender;
							this.bio = response.data.bio;
							this.avatar = response.data.avatar;
							this.birthday = response.data.birthDate;
						} else {

						}
					})
					.catch(error => {
						console.error('获取用户信息失败:', error);
						this.isLoggedIn = false; // 处理失败情况
					});
			},
			// 处理日期选择变化
			onDateChange(selectedDate) {
				this.birthday = selectedDate; // 更新生日数据
				this.updateUserInfo('birthday', selectedDate); // 发送更新请求
			},
			// 处理姓名、简介变化
			editField(field) {
				uni.navigateTo({
					url: `/packageMixture/pages/editSingleInfo/editSingleInfo?field=${field}&value=${this[field]}`,
				});

			},
			// 处理性别变化
			selectGender(gender) {
				this.gender = gender;
				this.updateUserInfo('gender', gender); // 更新性别后发送请求
			},
			goBack() {
				uni.navigateBack();
			},
			async updateUserInfo(field, value) {
				const userInfo = {};
				if (field === 'userAvatar') {
					userInfo.userAvatar = value;
				} else {
					userInfo[field] = value;
				}

				try {
					this.avatar = userInfo.userAvatar
					const response = await editUserInfo(userInfo);
					const userInfoStorage = uni.getStorageSync('userInfo');
						const userInfoS = JSON.parse(userInfoStorage);
						if (field === 'userAvatar') {
							userInfoS.avatar = value;
						} else if(field === 'name') {
							userInfoS.nickname = value;
						}else if(field === 'birthday') {
							userInfoS.birthDate = value;
						}
						else{
							userInfoS[field] = value;
						}
						uni.setStorageSync('userInfo', JSON.stringify(userInfoS));
					if (response.code !== 200) {
						uni.showToast({
							title: '信息更新失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('更新用户信息失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			},
		}
	}
</script>

<style scoped>
	.container {
		width: 750rpx;
		min-height: 100vh;
		background-color: white;
		position: relative;
	}

	.header {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		/* 水平居中 */
		padding-top: 80rpx;
		padding-bottom: 30rpx;
		padding-left: 32rpx;
		padding-right: 32rpx;
		position: relative;
	}

	.back-button {
		width: 64rpx;
		height: 64rpx;
		padding-top: 10rpx;
		align-items: center;
		/* 让图标在 back-button 内居中 */
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		left: 32rpx;
		/* 确保在左侧 */
	}

	.title {
		font-size: 32rpx;
		font-weight: 400;
	}

	.avatar-container {
		display: flex;
		justify-content: center;
		margin-top: 10rpx;
		margin-bottom: 60rpx;
	}

	.img-boxs {
		width: 100px;
		height: 100px;
		border-radius: 100%;
		position: relative;
		overflow: hidden;
	}

	.img-boxs image {
		width: 100px;
		height: 100px;
		border-radius: 100%;
		margin-bottom: 10px;
	}

	.img-boxs cover-view {
		width: 100px;
		height: 40px;
		text-align: center;
		color: #fff;
		background-color: rgba(107, 96, 99, .4);
		position: absolute;
		left: 50%;
		top: 66%;
		transform: translate(-50%, 0);
	}


	.gender-switch {
		display: flex;
		gap: 20rpx;
	}

	.man-icon {
		width: 60rpx;
		/* 设置宽度 */
		height: 60rpx;
		/* 设置高度 */
		margin-top: 6rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.woman-icon {
		width: 60rpx;
		/* 设置宽度 */
		height: 60rpx;
		/* 设置高度 */
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.man-image {
		width: 85%;
		/* 让图片宽度占满父容器 */
		height: 85%;
		/* 让图片高度占满父容器 */
		object-fit: cover;
		/* 保持宽高比，裁剪超出部分 */
	}

	.woman-image {
		width: 100%;
		/* 让图片宽度占满父容器 */
		height: 100%;
		/* 让图片高度占满父容器 */
		object-fit: cover;
		/* 保持宽高比，裁剪超出部分 */
	}

	.form-container {
		padding: 0 32rpx;
	}

	.form-item {
		display: flex;
		justify-content: space-between;
		/* 将子元素分散到两边 */
		align-items: center;
		height: 88rpx;
		border-bottom: 1rpx solid #DDDDDD;
	}

	.label {
		color: #7B7B7B;
		font-size: 28rpx;
	}

	.value {
		color: #181818;
		font-size: 28rpx;
		flex-grow: 1;
		/* 让输入框占用剩余空间 */
		text-align: right;
		/* 输入内容右对齐 */
	}
</style>